package com.jack.leetcode.eachProblem06;

import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class 单词拆分 {

    public static void main(String[] args) {
        System.out.println(wordBreak("leetcode", Arrays.asList("leet", "code")));
        System.out.println(wordBreak("applepenapple", Arrays.asList("apple", "pen")));
        System.out.println(wordBreak("catsandog", Arrays.asList("cats", "dog", "sand", "and", "cat")));
    }

    public static boolean wordBreak(String s, List<String> wordDict) {
        Set<String> wordSet = new HashSet<>(wordDict);
        int m = s.length();
        boolean[] dp = new boolean[m + 1];
        dp[0] = true;
        for (int i = 0; i <= m; i++) {
            for (int j = 0; j < m; j++) {
                if (dp[j] && wordSet.contains(s.substring(j, i))) {
                    dp[i] = true;
                    break;
                }
            }
        }
        return dp[m];
    }

//超时
//    public static boolean wordBreak(String s, List<String> wordDict) {
//        return canBeSplit(s, wordDict, 0);
//    }
//
//    private static boolean canBeSplit(String s, List<String> wordDictm, int j){
//        int m = s.length();
//        if(j >= m){
//            return true;
//        }
//        for (String w : wordDictm) {
//            if(s.charAt(j) == w.charAt(0)){
//                int n = w.length();
//                if(j + n <= m && s.substring(j, j + n).equalsIgnoreCase(w)){
//                    if(canBeSplit(s, wordDictm, j+n)){
//                        return true;
//                    }
//                }
//            }
//        }
//        return false;
//    }
}
